package com.example.room.repository;

import android.content.Context;
import android.os.AsyncTask;

import androidx.lifecycle.LiveData;

import com.example.room.dao.TeamMemberDao;
import com.example.room.database.MyDatabase;
import com.example.room.entity.TeamMember;

import java.util.List;

public class TeamMemberRepository {
    LiveData<List<TeamMember>> members;
    TeamMemberDao teamMemberDao;

    public TeamMemberRepository(Context context) {
        //获取数据库实例，数据库采用单例模式
        MyDatabase database = MyDatabase.getInstance(context.getApplicationContext());
        teamMemberDao = database.getTeamMemberDao();
        members = teamMemberDao.getAllTeamMember();
    }



    public LiveData<List<TeamMember>> getAllTeamMember() {
        return members;
    }

    public void insertTeamMember(TeamMember... teamMembers) {
        new InsertTeamMemberAsyncTask(teamMemberDao).execute(teamMembers);
    }

    public static class InsertTeamMemberAsyncTask extends AsyncTask<TeamMember,Void,Void>{

        TeamMemberDao teamMemberDao;

        public InsertTeamMemberAsyncTask(TeamMemberDao teamMemberDao) {
            this.teamMemberDao = teamMemberDao;
        }

        @Override
        protected Void doInBackground(TeamMember... teamMembers) {
            teamMemberDao.insertTeamMember(teamMembers);
            return null;
        }
    }

    public void deleteAllMaster() {
        new DeleteAllMasterAsynctask(teamMemberDao).execute();
    }

    public static class DeleteAllMasterAsynctask extends AsyncTask<Void,Void,Void> {
        TeamMemberDao teamMemberDao;

        public DeleteAllMasterAsynctask(TeamMemberDao teamMemberDao) {
            this.teamMemberDao = teamMemberDao;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            teamMemberDao.deleteAll();
            return null;
        }
    }
}
